<?php


namespace app\middleware;


use app\exception\TokenException;
use xiaodi\JWTAuth\Facade\Jwt;

class ApiLoginMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @throws TokenException
     */
    public function handle($request, \Closure $next)
    {
        $notLogin = [
            "/api/user/register",
            "/api/user/smssend",
            "/api/user/pwdlogin",
            "/api/user/codelogin",
        ];
        $requestUrl = strtolower($request->baseUrl());
        if (!in_array($requestUrl, $notLogin)) {
            if ($requestUrl == "/api/user/search") {
                if (!empty($request->header()['authorization'])) {
                    $token = substr($request->header()['authorization'], 7);
                    $this->checkToken($request, $token);
                }
            } else {
                $token = getHeaderToken();
                $this->checkToken($request, $token);
            }
        }
        return $next($request);
    }

    public function checkToken($request, $token)
    {
        try {
            Jwt::verify($token);
        } catch (\Exception $e) {
            throw new TokenException($e->getMessage());
        }
        $request->user = getUserSimpleInfo($token)['data'];
    }
}